// JORGE FERNANDO GOMEZ
// 1259371
// 189631
// LEC A1
// MARTIN MÜLLER
// D02
// YANG LIU


#include <string.h>
#include <curses.h>

#include "keyboardagent.h"
#include "gamestate.h"
#include "util.h"


static char controlLanderName[MAX_NAME] = {'\0'};


/* dispatchTable is hash table with input sequences as keys
 * and LActions pointers (struct of lander actions) as values.
 * Just did this to imitate Perl's table->{'user_input'}->function()
 * behaviour, and streamline code. */
hash * dispatchTable = NULL;

/* Structs that store some default responses to input. */
KBInput DefaultInput;
LActions LanderActionLeft, LanderActionRight,
         LanderActionThrust, LanderActionDefault;

void initDispatchTable ( void ) {
    dispatchTable = newHashTable(DISP_SIZE);
    hashInsert(dispatchTable, "0x104", &LanderActionLeft);
    hashInsert(dispatchTable, "0x105", &LanderActionRight);
    hashInsert(dispatchTable, "0x20", &LanderActionThrust);
    hashInsert(dispatchTable, "default", &LanderActionDefault);
}

hash* getDispatchTable ( void ) {
    return dispatchTable;
}

void setDefaultActions ( void ) {
    DefaultInput.left = KEY_LEFT;
    LanderActionLeft.doAction = &computeLeft;

    DefaultInput.right = KEY_RIGHT;
    LanderActionRight.doAction = &computeRight;

    DefaultInput.thrust = 0x20;
    LanderActionThrust.doAction = &computeThrust;

    LanderActionDefault.doAction = &printUsage;
}

int getInput ( void ) {
    int inputChar = wgetch(stdscr);
    return inputChar;
}

/* setLanderControl() copies a name string to the variable
 * controlLanderName[], which holds the name of the lander
 * which will be controlled by the keyboard. */
void setLanderControl ( char * name ){
    strcpy(controlLanderName, name);
}

/* getLanderControlName() returns the string stored in
 * controlLanderName. */
char* getLanderControlName ( void ) {
    return controlLanderName;
}

/* computeLeft() rotates the lander counterclockwise. */
void computeLeft ( void ) {
    updateLander(controlLanderName, 0, 0, LEFT);
    return;
}

/* computeRight() rotates the lander clockwise. */
void computeRight ( void ) {
    updateLander(controlLanderName, 0, 0, RIGHT);
    return;
}

/* computeThrust() computes a new lander velocity according
 * to the thrust value, controlLanderName's orientation.
 * It also switches a thruster flag stored for controlLanderName
 * in the gamestate module for other computations. */
void computeThrust ( void ) {
    landerComputeThrust(controlLanderName);
    landerActivateThrustFlag(controlLanderName);
    return;
}

/* printUsage() prints lander game usage. */
void printUsage ( void ) {
    printw("Use the left and right arrow keys to control the lander.  "
            " Use the spacebar to active the thruster.");
    return;
}
